import { SetStateAction, useEffect, useRef, useState } from 'react';
import { AiEditor } from 'aieditor';
import 'aieditor/dist/style.css';
import { getToken } from '../login/loginApi';
import FormatConverter from '../components/FormatConverter';
import { useLocation } from 'react-router-dom';
const apiHost = import.meta.env.VITE_API_HOST || '';

type FixItem = {
  original: string;
  suggestion: string[];
  adopt_suggestions: string;
};
function AiEditCustom() {
  const [showFormatConverter, setShowFormatConverter] = useState(false);
  // 用于处理后端返回的文件名
  const [fileName, setFileName] = useState('');
  const [title, setTitle] = useState('');
  const [fileStorageId, setFileStorageId] = useState('e787c8.docx');
  //定义 ref
  const divRef = useRef(null);
  const aiEditorRef = useRef<AiEditor | null>(null); // 明确指定 aiEditorRef 的类型

  // TODO 文件审核传递过来的建议
  const location = useLocation();
  const suggestions = location.state?.suggestions as FixItem[];
  const storageKey = location.state?.storageKey;

  //初始化 AiEditor
  useEffect(() => {
    if (divRef.current) {
      const aiEditor = new AiEditor({
        element: divRef.current,
        placeholder: '点击输入内容...',
        content: '',
        ai: {
          models: {
            // spark: {
            //   protocol: 'wss',
            //   appId: 'daed94b1',
            //   apiKey: '63b1568d8a0f08228f1ed5e2a16fa6e1',
            //   apiSecret: 'YzM5NTdjODUwYWFmYzk1YTQwNWEwOTZi',
            //   version: 'v3.5',
            // },
            custom: {
              url: apiHost + '/conversion/stream',
              method: 'POST',
              headers: () => {
                return {
                  'Content-Type': 'application/json',
                  Authorization: `Bearer ${getToken()}`,
                };
              },
              messageWrapper: (message: string) => {
                const requestBody = {
                  question: message,
                  conversion_name: 'AiEdit测试数据',
                  stream: true,
                };
                return JSON.stringify(requestBody);
              },
              messageParser: (message: string) => {
                console.log('messageParser', message);
                return {
                  role: 'assistant',
                  content: message,
                };
              },
            },
          },
          bubblePanelEnable: true,
        },
      });

      aiEditorRef.current = aiEditor;

      // TODO ,触发接口获取源文件的全文,进行替换
      console.log('suggestions数据:', suggestions);
      console.log('suggestions来自的文件key:', storageKey);
      if (suggestions && aiEditorRef.current) {
        const fetchData = async () => {
          try {
            const response = await fetch(
              `${apiHost}/documents/auditByGpt/storageKey/content/` +
                storageKey,
              {
                method: 'GET',
                headers: {
                  'Content-Type': 'application/json',
                  Authorization: `Bearer ${getToken()}`,
                },
              },
            );

            if (!response.ok) {
              throw new Error(
                `获取${storageKey}失败, 状态码：${response.status}`,
              );
            }
            const fileContent = await response.json(); // 使用await等待json解析完成
            // 2. 根据suggestions里对原文内容做替换

            let updatedContent = fileContent.data;

            suggestions.forEach((item) => {
              // 仅当item.adopt_suggestions不为空时，才执行替换操作
              if (item.adopt_suggestions) {
                const originalTextWithoutTags = item.original.replace(
                  /<\/?ais-highlight-0000000000>/g,
                  '',
                );
                updatedContent = updatedContent
                  .split(originalTextWithoutTags)
                  .join(item.adopt_suggestions);
              }
            });
  
            // 将最后替换的内容放入编辑器,并回调，不管结果如何
            aiEditor.focus().insert(updatedContent);
          } catch (error) {
            console.error('Error updating editor content:', error);
            alert(`获取${storageKey}失败`);
          }
        };

        fetchData();
      }

      return () => {
        aiEditor.destroy();
      };
    }
  }, [apiHost, getToken, storageKey, suggestions]); // 添加相关依赖到依赖数组中



  
  const toggleFormatConverter = () => {
    setShowFormatConverter((prevState) => !prevState);
  };

  const handleFormatOutput = (output: string) => {
    if (aiEditorRef.current) {
      aiEditorRef.current.focus().insert(output);
    }

    setShowFormatConverter(false);
  };

  const handleGPTFill = async () => {
    if (!title) {
      alert('请输入标题');
      return;
    }

    let markdownContent = '';

    // 如果aiEditorRef存在，则尝试获取Markdown内容
    if (aiEditorRef.current) {
      try {
        markdownContent = await aiEditorRef.current.getMarkdown();

        if (!markdownContent) {
          alert('内容不能为空');
          return;
        }
      } catch (error) {
        console.error('获取Markdown内容失败:', error);
        alert('获取编辑器内容失败');
        return;
      }
    }

    console.log('markdownContent:', markdownContent);

    // 准备请求体
    const requestBody = {
      title: title,
      tags: ['brain science'], // 根据需要可以动态调整
      content: markdownContent, // 将aiedit里的内容全部填充进去
    };

    try {
      const response = await fetch(apiHost + '/documents/markdown/docx', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${getToken()}`,
        },
        body: JSON.stringify(requestBody),
      });

      if (!response.ok) {
        throw new Error('Network response was not ok');
      }

      const data = await response.json();
      if (data.status === 'success') {
        setFileName(data.data.file);
        handleClearEditor();
        alert(`填充中--GPT填写文件名: ${data.data.file}`);
      }
    } catch (error) {
      alert('至少得存在一个插槽标签');
    }
  };
  // 处理标题输入变化
  const handleTitleChange = (event: {
    target: { value: SetStateAction<string> };
  }) => {
    setTitle(event.target.value);
  };

  // 一键清空编辑器
  const handleClearEditor = () => {
    if (aiEditorRef.current) {
      aiEditorRef.current.clear();
    }
  };
  // 表单条件查询
  const handleFileStorageIdChange = (e: {
    target: { value: SetStateAction<string> };
  }) => {
    setFileStorageId(e.target.value);
  };

  const handleSearch = async () => {
    if (!fileStorageId) {
      alert('请输入文件存储ID');
      return;
    }

    try {
      // 假设这是调用后端接口的函数，这里使用fetch进行演示
      const response = await fetch(apiHost + '/documents/gpt-return/docx', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${getToken()}`,
        },
        body: JSON.stringify({ file_storage_id: fileStorageId }),
      });

      const data = await response.json();

      if (data.status === 'success') {
        if (data.data) {
          if (aiEditorRef.current) {
            aiEditorRef.current.focus().insert(data.data);
          }
        } else {
          alert('GPT还未填写完成');
        }
      } else {
        alert(data.msg || '查询失败');
      }
    } catch (error) {
      alert('GPT还未填写完成');
    }
  };

  // handleGenerate  生成最终文件
  const handleGenerate = async () => {
    if (!fileStorageId) {
      alert('请输入文件存储ID');
      return;
    }
    if (!title) {
      alert('请输入标题');
      return;
    }
    try {
      let editorContent = '';
      if (aiEditorRef.current) {
        try {
          editorContent = await aiEditorRef.current.getMarkdown();
        } catch (error) {
          console.error('获取Markdown内容失败:', error);
          alert('获取编辑器内容失败');
          return;
        }
      }
      // 调用后端接口，这里替换为你的接口地址
      const response = await fetch(apiHost + '/documents/gpt-gen/docx', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${getToken()}`,
        },
        body: JSON.stringify({
          title: title,
          file_storage_id: fileStorageId,
          content: editorContent,
        }),
      });

      const data = await response.json();

      if (data.status === 'success') {
        alert(`生成成功--文件名: ${data.data.file}`);
        if (aiEditorRef.current) {
          aiEditorRef.current.clear();
        }
        setTitle('');
      } else {
        alert(data.msg || '生成失败');
      }
    } catch (error) {
      console.error('生成异常', error);
      alert('生成异常，请稍后再试');
    }
  };

  return (
    <>
      <h1 className="my-5 text-center text-2xl font-bold">
        Welcome to the chatCRO GPT 🐖 AIedit!
      </h1>
      <div className="mb-5">
        <h3 className="mb-2 text-lg font-semibold">标题：</h3>
        <input
          type="text"
          value={title}
          onChange={handleTitleChange}
          placeholder="请输入标题"
          className="w-full rounded border border-gray-300 p-2"
        />
      </div>

      {showFormatConverter && <FormatConverter onOutput={handleFormatOutput} />}

      <div ref={divRef} style={{ height: '600px' }} />

      <div className="fixed bottom-10 right-10 space-y-2">
        <button
          onClick={toggleFormatConverter}
          className="mr-2 rounded bg-green-500 px-4 py-2 text-white shadow"
        >
          {showFormatConverter ? '关闭插槽' : '打开插槽'}
        </button>

        {/* GPT填充功能的按钮 */}
        <button
          onClick={handleGPTFill}
          className="mr-2 rounded bg-blue-500 px-4 py-2 text-white shadow"
        >
          GPT填充
        </button>
        {/* 清空编辑器内容的按钮 */}
        <button
          onClick={handleClearEditor}
          className="mr-2 rounded bg-yellow-500 px-4 py-2 text-white shadow"
        >
          清空内容
        </button>

        {/* 新增的生成按钮 */}
        <button
          onClick={handleGenerate}
          className="rounded bg-purple-500 px-4 py-2 text-white shadow"
        >
          生成新文件
        </button>

        {/* 表单条件查询 */}
        <div className="mt-2 flex items-center space-x-2">
          <input
            type="text"
            value={fileStorageId}
            onChange={handleFileStorageIdChange}
            placeholder="请输入查询条件"
            className="flex-grow rounded border border-gray-300 p-2"
          />
          <button
            onClick={handleSearch}
            className="rounded bg-blue-500 px-4 py-2 text-white shadow"
          >
            查询GPT填写内容
          </button>
        </div>
      </div>
    </>
  );
}

export default AiEditCustom;
